//
//  LuckyReadyVC.m
//  SMTools
//
//  Created by fengsh on 2018/12/26.
//  Copyright © 2018年 fengsh. All rights reserved.
//

#import "LuckyReadyVC.h"
#import <Masonry/Masonry.h>
#import "LuckyApi.h"
#import "LuckyUtils.h"
#import "LuckyProject.h"
#import "LuckyScreenWnd.h"
#import "LuckyNotifyWnd.h"
#import "LuckyNumberWnd.h"

@interface LuckyReadyVC ()<NSTableViewDelegate,NSTableViewDataSource>
@property (weak) IBOutlet NSTableView                           *tablist;
@property (nonatomic, strong) NSMutableArray                    *dataset;
@property (nonatomic, strong) LuckyScreenWnd                    *screen;
@property (nonatomic, strong) LuckyNotifyWnd                    *notify;
@property (nonatomic, strong) LuckyNumberWnd                    *processWnd;
@property (nonatomic, assign) NSInteger                         currentflag;
@end

@implementation LuckyReadyVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do view setup here.
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshData) name:@"kNtf_Refresh_List" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:) name:NSWindowWillCloseNotification object:nil];
    
//    self.tablist.gridStyleMask = NSTableViewSolidHorizontalGridLineMask;
    self.dataset = [NSMutableArray array];
    _currentflag = 2;
    [self refreshData];
}

- (void)refreshData
{
    NSDictionary *p = @{@"remainCountFlag":[NSString stringWithFormat:@"%ld",(long)_currentflag]};
    [[LuckyApi api]lucky_api_post_queryActiveList:p comletion:^(id respobj, NSError *error) {
        if (!error) {
            NSString *retcode = respobj[@"retcode"];
            if ([retcode isEqualToString:@"00000"]) {
                NSArray *list = respobj[@"data"];
                [self.dataset removeAllObjects];
                for (NSDictionary *item in list) {
                    LuckyProject *lp    = nil;

                    lp = [[LuckyProject alloc]initWithContext:nil];

                    lp.company          = [LuckyUtils lucky_dictionaryvalue:item[@"company"]];
                    lp.count            = [item[@"count"]integerValue];
                    lp.id               = [item[@"id"]longLongValue];
                    lp.number           = (int32_t)[item[@"number"]integerValue];
                    lp.prize_level_name = [LuckyUtils lucky_dictionaryvalue:item[@"prizeLevelName"]];
                    lp.prize_name       = [LuckyUtils lucky_dictionaryvalue:item[@"prizeName"]];
                    lp.remain_count     = [item[@"remainCount"]integerValue];
                    lp.scope            = [LuckyUtils lucky_dictionaryvalue:item[@"scope"]];
                    [self.dataset addObject:lp];
                }
                
                [self.tablist reloadData];
            } else {
                NSString *msg = respobj[@"msg"];
                [LuckyUtils lucky_show:msg];
            }
        }
    }];
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
    return self.dataset.count;
}

- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row
{
    return 30;
}

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    NSUserInterfaceItemIdentifier idf = tableColumn.identifier;
    NSTableCellView *cv = [tableView makeViewWithIdentifier:idf owner:nil];
    NSInteger colidx = [tableView columnWithIdentifier:idf];
    if (colidx == 0) {
        LuckyProject *lp = self.dataset[row];
        for (NSButton *button in cv.subviews) {
            
            if ([button.identifier isEqualToString:@"btn_ready"]) {
                [button setTitle:((lp.remain_count == lp.count) || (lp.remain_count != 0))?@"准备":@"结果"];
                [button setAction:@selector(onReadyGo:)];
            } else if ([button.identifier isEqualToString:@"btn_delete"]) {
                [button setAction:@selector(onDeleteGo:)];
            } else if ([button.identifier isEqualToString:@"show_result"]) {
                [button setEnabled:(lp.count != lp.remain_count)];
                [button setAction:@selector(onShowResult:)];
            }
            [button setTag:row];
            [button  setTarget:self];
            
        }
    } else {
        LuckyProject *lp = self.dataset[row];
        switch (colidx) {
            case 1:
            {
                [cv.textField setStringValue:(lp.remain_count == lp.count)?@"未抽奖": (lp.remain_count == 0) ? @"已抽奖" : @"已抽部分"];
            }
                break;
            case 2:
            {
                [cv.textField setStringValue:lp.prize_level_name?:@""];
            }
                break;
            case 3:
            {
                [cv.textField setStringValue:lp.prize_name?:@""];
            }
                break;
            case 4:
            {
                [cv.textField setStringValue:[NSString stringWithFormat:@"%hd",lp.count]];
            }
                break;
            case 5:
            {
                [cv.textField setStringValue:[NSString stringWithFormat:@"%d",lp.number]];
            }
                break;
            case 6:
            {
                NSString * s = nil;
                if ([lp.scope isEqualToString:@"1"]) {
                    s = @"全员";
                } else {
                    s = @"已中奖的不能参加";
                }
                
                [cv.textField setStringValue:s];
            }
                break;
            case 7:
            {
                [cv.textField setStringValue:lp.company?:@""];
            }
                break;
            default:
                break;
        }
        
    }
    
    return cv;
}

- (void)tableView:(NSTableView *)tableView didAddRowView:(NSTableRowView *)rowView forRow:(NSInteger)row
{
    if (row % 2 != 0) {
        rowView.backgroundColor = [NSColor windowBackgroundColor];
    }
}

- (void)tableView:(NSTableView *)tableView mouseDownInHeaderOfTableColumn:(NSTableColumn *)tableColumn
{
    NSLog(@"click %@",tableColumn.title);
}

- (void)onReadyGo:(NSButton *)sender
{
    
//    NSInteger idx = sender.tag;
//    id obj = self.dataset[idx];
//    if (obj) {
//        self.screen = [[LuckyScreenWnd alloc]initWithWindowNibName:@"LuckyScreenWnd"];
//        self.screen.currentProject = obj;
//        [self.screen.window center];
//        [self.screen showWindow:nil];
//    //    [NSApp beginModalSessionForWindow:self.screen.window];
//    }
//    return;
//
    NSInteger idx = sender.tag;
    LuckyProject *obj = self.dataset[idx];
    
    if (obj) { //只有一个轮次，直接投屏呗
        self.processWnd = [[LuckyNumberWnd alloc]initWithWindowNibName:@"LuckyNumberWnd"];
        self.processWnd.currentProject = obj;
        [self.processWnd.window center];
        
        [[NSApplication sharedApplication]runModalForWindow:self.processWnd.window];
        //        [self.processWnd showWindow:nil];
    }
}

///监听打开的窗口是否关闭，如果关了，把引用解除
- (void)windowWillClose:(NSNotification *)notification
{
    NSWindow* window = notification.object;
    if (window == self.screen.window) {
        self.screen = nil;
    } else if (window == self.notify.window) {
        self.notify = nil;
    } else if (window == self.processWnd.window) {
        [[NSApplication sharedApplication] stopModal];
        self.processWnd = nil;
    }
}

- (void)onDeleteGo:(NSButton *)sender
{
    //开奖了就不能删除了
    NSInteger idx = sender.tag;
    LuckyProject *obj = self.dataset[idx];
    if (obj.remain_count != obj.count) {
        [LuckyUtils lucky_show:@"已开奖,不能删除"];
        return;
    }
    
    NSAlert *alert = [[NSAlert alloc] init];
    [alert addButtonWithTitle:@"确定"];
    [alert addButtonWithTitle:@"取消"];
    [alert setMessageText:@"您确定要删除该奖项吗？"];
    [alert setInformativeText:@"删除后将不可恢复哦!!!"];
    [alert setAlertStyle:NSWarningAlertStyle];
    [alert beginSheetModalForWindow:self.view.window completionHandler:^(NSInteger result) {
        if (result == NSAlertFirstButtonReturn) {
            NSInteger row = sender.tag;
            LuckyProject *lp = self.dataset[row];
            
            [[LuckyApi api]lucky_api_post_deleteActive:@{@"id":@(lp.id)} comletion:^(id respobj, NSError *error) {
                if (!error) {
                    [self.dataset removeObjectAtIndex:row];
                    [self.tablist reloadData];
                }
            }];
        }
    }];
}

- (void)onShowResult:(NSButton *)sender
{
    NSInteger idx = sender.tag;
    LuckyProject *obj = self.dataset[idx];
    int64_t pid = obj.id;
    
    [[LuckyApi api]lucky_api_post_export:@{@"prizeLevelId":@(pid)} comletion:^(id respobj, NSError *error) {
        if (!error) {
            NSArray *arrDownloadPaths = NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory,NSUserDomainMask,YES);
            NSString *loadPathsPath = [arrDownloadPaths objectAtIndex:0];
            NSData *export = respobj;
            NSString *excel = [NSString stringWithFormat:@"%@.xls",obj.prize_level_name];
            NSString *p = [loadPathsPath stringByAppendingPathComponent:excel];
            NSError *err = nil;
            [export writeToFile:p options:NSDataWritingWithoutOverwriting error:&err];
            if (err) {
                NSLog(@"%@",err);
                [LuckyUtils lucky_show:[NSString stringWithFormat:@"导出excel异常! %@",err]];
            } else {
                [LuckyUtils lucky_show:@"导出成功!自动保存在下载目录!"];
            }
        } else {
            [LuckyUtils lucky_show:@"导出excel失败!"];
        }
    }];
}

- (IBAction)onRefresh:(id)sender
{
    _currentflag = 0;
    [self refreshData];
}

- (IBAction)onUnDo:(id)sender {
    _currentflag = 2;
    [self refreshData];
}

- (IBAction)onDo:(id)sender {
    _currentflag = 1;
    [self refreshData];
}

- (IBAction)onExportAll:(id)sender {
    [[LuckyApi api]lucky_api_post_export:@{} comletion:^(id respobj, NSError *error) {
        if (!error) {
            NSArray *arrDownloadPaths = NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory,NSUserDomainMask,YES);
            NSString *loadPathsPath = [arrDownloadPaths objectAtIndex:0];
            NSData *export = respobj;
            NSString *excel = [NSString stringWithFormat:@"%@.xls",@"所有结果"];
            NSString *p = [loadPathsPath stringByAppendingPathComponent:excel];
            NSError *err = nil;
            [export writeToFile:p options:NSDataWritingWithoutOverwriting error:&err];
            if (err) {
                NSLog(@"%@",err);
                [LuckyUtils lucky_show:[NSString stringWithFormat:@"导出excel异常! %@",err]];
            } else {
                [LuckyUtils lucky_show:@"导出成功!自动保存在下载目录!"];
            }
        } else {
            [LuckyUtils lucky_show:@"导出excel失败!"];
        }
    }];
}

///一次性操完所有奖项
- (IBAction)onAllFinish:(id)sender {
    [[LuckyApi api]lucky_api_post_finish_all:@{} comletion:^(id respobj, NSError *error) {
        if (!error) {
            NSString *recode = respobj[@"retcode"];
            NSString *msg = respobj[@"msg"];
            if ([recode isEqualToString:@"00000"]) {
                [LuckyUtils lucky_show:@"一键抽奖结束"];
            } else {
                [LuckyUtils lucky_show:msg];
            }
        }
    }];
}

@end
